
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.js"></script>
<style>
    .container-fluid{
        padding-left: 0px !important;
        padding-right: 0px !important;
    }
</style>
<?php
$this->breadcrumbs=array(
    'Businesses'=>array('index'),
    'Google Search',
);
?>
<div id="gsearch_wrapper">
    <div class="search_box_wrapper">
        <div class="search_box_item">
            <span>Name:</span>
            <input type="text" class="search_box_input" name="Search[name]" id="google_search_name">
        </div>
        <div class="search_box_item">
            <span>Adress:</span>
            <input type="text" class="search_box_input" name="Search[address]" id="google_search_address">
        </div>
        <div class="search_box_item">
            <input type="submit" class="search_box_submit" value="Search" id="google_search_button">
            <div id="loading_wrapper">
                <img id="loading_img" src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/img/loading.gif" />
            </div>

        </div>
    </div>
    <div id="map"></div>
    <div class="google_result_wrapper">
        <table id="table_result" class="table table-striped table-bordered" cellspacing="0" width="100%">
            <thead>
            <tr class="gresult_thead">
                <th>Add?</th>
                <th>Name</th>
                <th>Address</th>
                <th>State</th>
                <th>Website</th>
                <th>google_url</th>
                <th>gplace_id</th>
            </tr>
            </thead>
        </table>
    </div>


    <!--Contact Form -->
    <div id="contactdiv">
        <?php $form=$this->beginWidget('CActiveForm', array(
            'action'=> Yii::app()->createUrl('admin/business/insert'),
            'id'=>'contact',
            'enableAjaxValidation'=>false,
            'htmlOptions'=>array('class'=>'form-horizontal'),
        )); ?>
        <div id="gtitle_wrapper">
            <div id="gpopup_title"><span>Create Business</span></div>
            <div id="cancel"><i class="icon-remove"></i></div>
        </div>

        <?php echo $form->errorSummary($model, null, null, array('class'=>'alert alert-error')); ?>

        <div class="control-group">
            <?php echo $form->labelEx($model,'name', array('class'=>'control-label')); ?>
            <div class="controls">
                <?php echo $form->textField($model,'name',array('class'=>'business_input', 'id'=>'gform_name')); ?>
            </div>
        </div>

        <div class="control-group">
            <?php echo $form->labelEx($model,'address', array('class'=>'control-label')); ?>
            <div class="controls">
                <?php echo $form->textField($model,'address',array('class'=>'business_input', 'id'=>'gform_address')); ?>
            </div>
        </div>

        <div class="control-group">
            <?php echo $form->labelEx($model,'state_id', array('class'=>'control-label')); ?>
            <div class="controls">
                <?php echo $form->dropDownList($model,'state_id', CHtml::listData(States::model()->findAll(), 'id', 'name'),array('id'=>'gform_state')); ?>
            </div>
        </div>

        <div class="control-group">
            <?php echo $form->labelEx($model,'website', array('class'=>'control-label')); ?>
            <div class="controls">
                <?php echo $form->textField($model,'website',array('class'=>'business_input', 'id'=>'gform_website')); ?>
            </div>
        </div>

        <div class="control-group">
            <?php echo $form->labelEx($model,'google_url', array('class'=>'control-label')); ?>
            <div class="controls">
                <?php echo $form->textField($model,'google_url',array('class'=>'business_input', 'id'=>'gform_url')); ?>
            </div>
        </div>

        <div class="control-group">
            <?php echo $form->labelEx($model,'gplace_id', array('class'=>'control-label')); ?>
            <div class="controls">
                <?php echo $form->textField($model,'gplace_id',array('class'=>'business_input', 'id'=>'gform_place')); ?>
            </div>
        </div>

        <div class="form-actions" style="background-color: white;">
            <?php echo CHtml::button('Create',array('class'=>'btn btn-primary', 'onclick'=>'send();')); ?>
        </div>

        <?php $this->endWidget(); ?>
    </div>
</div>

<script>
    var table;
    var dataSet = [];

    $(document).ready(function() {
        $("#google_search_button").click(function () {
            if ($("#google_search_name").val() == "" && $("#google_search_address").val() == "") {
                alert("Please insert to the text box!!!");
            }
            else {
                $("#loading_img").show();

                if(table){
                    table.destroy();
                    dataSet = [];
                }

                var query = $("#google_search_name").val() + $("#google_search_address").val();
                query = query.replace(" ", "+");
                query = query.replace("&", "");

                var key = "AIzaSyBvStu4aSjMhquao3v_er5LI3PqP6NK5Os";
                var url = "https://maps.googleapis.com/maps/api/place/textsearch/json";

                var map;
                var service;
                var pyrmont = new google.maps.LatLng(37.1, -95.7);

                map = new google.maps.Map(document.getElementById('map'), {
                    center: pyrmont,
                    zoom: 15
                });

                var request = {
//                    location: pyrmont,
//                    radius: '50000',
                    query: query
                };

                service = new google.maps.places.PlacesService(map);
                service.textSearch(request, callback);
            }
        });

        $('#table_result').on( 'click', 'tr', function () {
            if ( !$(this).hasClass('selected') ) {
                table.$('tr.selected').removeClass('selected');
                $(this).addClass('selected');
            }
        } );

        // Add event listener for opening and closing details
        $('#table_result').on('click', 'td.result_add', function () {
            var tr = $(this).closest('tr');
            var row = table.row( tr );

            getRow(row.data());

            $("#contactdiv").css("display", "block");
        });

    });

    function callback(results, status, pagination) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            for (var i = 0; i < results.length; i++) {
//                console.log(results[i]);
                dataSet.push({
                    icon: '<i class="icon-plus"></i>',
                    name: results[i].name,
                    address: results[i].formatted_address,
                    state: '',
                    website : '',
                    google_url : '',
                    gplace_id : results[i].place_id
                });
            }
        }
        if (pagination.hasNextPage) {
            pagination.nextPage();
        }
        else{
            table = $('#table_result').DataTable({
                "data": dataSet,
                "columns": [
                    {
                        "className":      'result_add',
                        "orderable":      false,
                        "data":           "icon"
                    },
                    { "data": "name", "class": "test_class" },
                    { "data": "address", "class": "test_class" },
                    { "data": "state", "class": "test_class" },
                    { "data": "website", "class": "test_class" },
                    { "data": "google_url", "class": "test_class" },
                    { "data": "gplace_id", "class": "test_class" },
                ],
                "bSort" : false
            });

            $("#loading_img").hide();
        }
    }

    function getRow(data){
        console.log(data.name);
        $('#gform_name').val(data.name);
        $('#gform_address').val(data.address);
        $('#gform_place').val(data.gplace_id);
    }

    $(document).ready(function() {
        $("#contact #cancel").click(function() {
            $("#contactdiv").hide();
        });
        // Contact form popup send-button click event.
        $("#send").click(function() {
            var name = $("#gform_name").val();
            var address = $("#gform_address").val();
            var place = $("#gform_place").val();
            if (name == "" || address == "" || place == ""){
                alert("Please fill all required fields!");
            }
        });
    });

    function send(){
        var data=$("#contact").serialize();
        $.ajax({
            type: 'POST',
            url: '<?php echo Yii::app()->createUrl('admin/business/insert'); ?>',
            data:data,
            success:function(datarespone){
                if(datarespone.result = "OK"){
                    alert("Create business successful!");
                }
                $("#contactdiv").hide();
            },
            error: function(data) { // if error occured
                alert("Error occured.please try again");
                alert(data);
            },

            dataType:'json'
        });

    }

</script>